package org.ws.lifebacklog.util;

import java.io.IOException;
import java.util.List;

import android.content.res.AssetManager;

/**
 * @author exebichi
 * 
 */
public class DatabaseUtil {

	/**
	 * Build sql query like this "<code>_id [NOT] in (id1,id2,id3)</code>"
	 * 
	 * @param ids - array of included params.
	 * @param isInclude - use true for "_id in" query or false for "_id NOT in"
	 * */
	public static String buildQueryIN(String[] ids, boolean isInclude) {
		String in = "";
		if (ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				in = in + ids[i] + ",";
			}
			in = in.substring(0, in.length() - 1);
		}
		return String.format("_id %s in (%s)", isInclude ? "" : "NOT", in);
	}

	/**
	 * Get sql init scripts
	 * 
	 * @param version - current db version. 0 for full initialization
	 * @return list of sql string for execution.
	 * @throws IOException
	 */
	public static int getSQLScripts(AssetManager am, List<String> sqls, int version) throws IOException {
		String[] versions = am.list("sql");
		for (int i = version - 1; i < versions.length; i++) {
			String versionPath = "sql/" + versions[i];
			String[] scripts = am.list(versionPath);
			for (String scriptName : scripts) {
				String sqlPath = versionPath + "/" + scriptName;
				Logger.i(DatabaseUtil.class, "add script to execute list: " + sqlPath);
				String sql = FileUtils.readAsString(am.open(sqlPath));
				if (sql != null && sql.trim().length() > 0) {
					sqls.add(sql);
				}
			}
		}
		return versions.length;

	}

	/**
	 * @return
	 */
	public static int getDbVersion(AssetManager am) {
		try {
			String[] versions = am.list("sql");
			return versions.length > 0 ? versions.length : 1;
		} catch (Exception e) {
			Logger.e(DatabaseUtil.class, e);
		}
		return 1;
	}
}
